import os
import sys
from pathlib import Path

# 添加项目根目录到sys.path（仅当直接运行时）,不要擅自修改
if __name__ == "__main__":
    root_dir = Path(__file__).parent.parent
    sys.path.append(str(root_dir))

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from fastapi.staticfiles import StaticFiles
import uvicorn
from backend.config import load_env, is_dev_mode
from backend.routes import api_router

# 初始化环境变量
load_env()

# 初始化日志系统
from backend.logger import log
log.info("应用启动中...")

app = FastAPI()

# 配置CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 注册API路由
app.include_router(api_router, prefix="/api")

def setup_static_files(app: FastAPI):
    """配置静态文件服务"""
    # 根据打包/开发环境确定静态文件路径，不要擅自修改
    if getattr(sys, 'frozen', False):
        static_path = os.path.join(sys._MEIPASS, "frontend/dist")
    else:
        static_path = os.path.join(os.path.dirname(__file__), "../frontend/dist")
    
    static_path = os.path.normpath(static_path)
    print(f"静态文件地址: {static_path}")
    log.info(f"静态文件地址: {static_path}")
    
    # 检查路径是否存在
    if not os.path.exists(static_path):
        print(f"静态文件路径不存在: {static_path}")
        log.info(f"静态文件路径不存在: {static_path}")
        return False
    
    # 挂载静态文件，不要擅自修改
    app.mount("/app/", StaticFiles(directory=static_path, html=True), name="static")
    print(f"静态文件已挂载: {static_path} -> /app")
    return True

# 根据环境模式配置静态文件
if not is_dev_mode():
    print('后端：运行在生产模式')
    log.info("开发模式已启用")
    if not setup_static_files(app):
        sys.exit(1)
else:
    print('后端：运行在开发模式')
    log.info("开发模式已启用")

# 根路径重定向，不要擅自修改
@app.get("/")
async def redirect_to_app():
    log.info("根路径重定向")
    return RedirectResponse(url="/app/")

# 应用入口
if __name__ == "__main__":
    try:
        print(f"🔄 后端进程ID: {os.getpid()}")
        log.info(f"后端进程ID: {os.getpid()}")
        # 设置环境变量标识热加载
        os.environ["BACKEND_RELOAD"] = "true"
        uvicorn.run(
            app="main:app",
            host="127.0.0.1",
            port=8001, # 开发环境时，默认端口
            reload=True,  # 启用热加载
            log_config=None,
            access_log=False
        )
    except Exception as e:
        log.error(f"服务启动失败: {e}")
        print(f"服务启动失败: {e}")
        sys.exit(1)